control.onEvent(4800, 4801, function () {
    // 1 dot = 50cm range
    basic.showLeds(`
        . . . . #
        . . . . .
        . . . . .
        . . . . .
        . . . . .
        `)
    range = 50
})
control.onEvent(4800, 4803, function () {
    // 3 dots = 150cm range
    basic.showLeds(`
        . . . . #
        . . . . #
        . . . . #
        . . . . .
        . . . . .
        `)
    range = 150
})
control.onEvent(4800, 4802, function () {
    // 2 dots = 100cm range
    basic.showLeds(`
        . . . . #
        . . . . #
        . . . . .
        . . . . .
        . . . . .
        `)
    range = 100
})
let heading = 0
let cm = 0
let range = 0
music.play(music.stringPlayable("E B C5 A B G A F ", 120), music.PlaybackMode.InBackground)
for (let index = 0; index < 4; index++) {
    basic.showIcon(IconNames.Heart)
    basic.pause(200)
    basic.showIcon(IconNames.SmallHeart)
    basic.pause(200)
}
// 2 dots = 100cm range
basic.showLeds(`
    . . . . #
    . . . . #
    . . . . .
    . . . . .
    . . . . .
    `)
// sonar range [2, 400]cm
// but I just use 4 ~ 50/100/150
// for easy demo
range = 100
led.setBrightness(82)
radio.setGroup(18)
// heart beat
loops.everyInterval(1000, function () {
    led.toggle(2, 2)
})
control.inBackground(function () {
    while (true) {
        cm = sonar.ping(
        DigitalPin.P1,
        DigitalPin.P2,
        PingUnit.Centimeters
        )
        heading = input.compassHeading()
        if (cm >= 4 && cm <= range) {
            radio.sendValue("heading", heading)
            radio.sendValue("cm", cm)
            pins.digitalWritePin(DigitalPin.P8, 1)
        } else {
            pins.digitalWritePin(DigitalPin.P8, 0)
        }
        cm = 0
        // rotate platform mid. speed = 4 rpm.
        // 41.7 ms / deg
        // ref: 2rpm -> 83ms/deg; 6rpm -> 28ms/deg
        basic.pause(40)
    }
})
